package com.lxw.report.meta.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.lxw.report.meta.Exception.CommonException;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;

/**
 * @author lxw
 * @time 2022/4/2 15:11
 */
public final class ValidateUtils {
    private ValidateUtils() {
    }

    /**
     * validate主动校验方式
     *
     * @param validateObject 进行校验的对象
     * @param <T> 传递的校验类型
     * @throws CommonException 服务异常
     */
    public static <T> void validate(@Valid T validateObject) throws CommonException {
        Set<ConstraintViolation<@Valid T>> validateSet = Validation
                .buildDefaultValidatorFactory()
                .getValidator()
                .validate(validateObject);
        //出现异常抛出
        if (CollectionUtil.isNotEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + ";" + m2)
                    .orElse("参数错误");
            throw new CommonException(messages);
        }
    }
}

